<?php

namespace app\api\controller;
    use think\Controller;

    ini_set('memory_limit',-1); //要有足够大的内存来允许处理上传的文件
    set_time_limit(0); //防止超时

    class Upload extends Controller
    {
        private $filepath; //上传目录
        private $tmpPath; //PHP文件临时目录
        private $blobNum; //第几个文件块
        private $totalBlobNum; //文件块总数
        private $fileName; //文件名

        public function __construct($tmpPath,$blobNum,$totalBlobNum,$fileName,$filepath){
            $this->tmpPath = $tmpPath;
            $this->blobNum = $blobNum;
            $this->totalBlobNum = $totalBlobNum;
            $this->fileName = $fileName;
            $this->filepath = $filepath;
            $this->moveFile();
            $this->fileMerge();
        }

        private function fileMerge(){
            if($this->blobNum == $this->totalBlobNum){
                // 此处文件不应该拼接，应该是追加入内
                // 实测修改后php占用很少的内存也可以实现大文件的上传和拼接操作
                for($i=1; $i<= $this->totalBlobNum; $i++){
                    $blob = '';
                    $blob = file_get_contents($this->filepath.'/'. $this->fileName.'__'.$i);
                    file_put_contents($this->filepath.'/'. $this->fileName, $blob, FILE_APPEND );
                    unset($blob);
                }
                $this->deleteFileBlob();
            }
        }

        //删除文件块
        private function deleteFileBlob(){
            for($i=1; $i<= $this->totalBlobNum; $i++){
                @unlink($this->filepath.'/'. $this->fileName.'__'.$i);
            }
        }


        private function moveFile(){
            $this->touchDir();
            $filename = $this->filepath.'/'. $this->fileName.'__'.$this->blobNum;
            move_uploaded_file($this->tmpPath,$filename);
        }

        //API返回数据
        public function apiReturn(){
            if($this->blobNum == $this->totalBlobNum){
                if(file_exists($this->filepath.'/'. $this->fileName)){
                    $data['code'] = 2;
                    $data['msg'] = 'success';
                    $data['file_path'] = $this->fileName;
                    $data['file_name'] = substr($this->fileName,0,strrpos($this->fileName, '.'));
                    $data['file_extension'] = substr(strrchr($this->fileName, '.'), 1);
                }
            }else{
                if(file_exists($this->filepath.'/'. $this->fileName.'__'.$this->blobNum)){
                    $data['code'] = 1;
                    $data['msg'] = 'waiting';
                    $data['file_path'] = '';
                }
            }
            header('Content-type: application/json');
            echo json_encode($data);
        }


        private function touchDir(){
            if(!file_exists($this->filepath)){
                return mkdir($this->filepath);
            }
        }

    }
